﻿
using System;
using MediatR;
using Casamiel.Domain.Response;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using System.Net.Http;
using Casamiel.Common;
using Microsoft.Extensions.Options;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Casamiel.Common.Extensions;
using System.Collections.Generic;
using Casamiel.Domain.Response.IC;
using Casamiel.Domain.Request;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// MallOrderPreview function too hard. I'll go crazy if i code
	/// </summary>
	public sealed class MallOrderPreviewCommandHandler : BaseCommandHandler, IRequestHandler<MallOrderPreviewCommand, BaseResult<MallOrderPreviewReponse>>
	{
		private readonly IMemberRepository _memberRepository;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly IMbrStoreRepository _mbrStoreRepository;
		public MallOrderPreviewCommandHandler(IMemberRepository memberRepository, IMbrStoreRepository mbrStoreRepository, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)

		{
			_memberRepository = memberRepository;
			_memberCouponRepository = memberCouponRepositor;
			_mbrStoreRepository = mbrStoreRepository;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<MallOrderPreviewReponse>> Handle(MallOrderPreviewCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			if (request.GoodsList == null && !request.GoodsList.Any()) {
				return new BaseResult<MallOrderPreviewReponse>(null, 9999, "产品不能为空");
			}

			var storeInfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
			if (storeInfo == null) {
				return new BaseResult<MallOrderPreviewReponse>(null, 9999, "门店信息有误");
			}
			var url = "MWeb/v3/Index/GetConfig";

			decimal FreightMoney = 0;
			decimal Discount = 0;
			var youxuanOrderMoney = 0;
			var result = await PostAsync(url, "").ConfigureAwait(false);
			var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
			if (dynamicdata["resultNo"].ToString() == "00000000") {
				var rule = JsonConvert.DeserializeObject<dynamic>(dynamicdata["data"].ToString());
				FreightMoney = rule.youxuanFreightMoney;
				youxuanOrderMoney = rule.youxuanOrderMoney;
			} else {
				return new BaseResult<MallOrderPreviewReponse>(null, 9999, "运费规则出错了");
			}

			var OrderAmount = request.GoodsList.Sum(c => c.GoodsQuantity * c.Price);
			if (OrderAmount >= youxuanOrderMoney) {
				FreightMoney = 0;
			}

			var entity = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (entity == null) {
				return new BaseResult<MallOrderPreviewReponse>(null, 9999, "会员不存在");
			}

			if (request.DiscountList != null && request.DiscountList.Any()) {
				decimal ticketInfoPrice;
				ICResult ticketLimit;
				if (request.DiscountList.Count > 1) {
					return new BaseResult<MallOrderPreviewReponse>(null, 9999, "券只能用一张");
				}
				if (request.DiscountList[0].DiscountCouponType == 1) {
					if (request.GoodsList.Any(c => c.GoodsRelationId == 589873)) {
						return new BaseResult<MallOrderPreviewReponse>(null, 9999, "抱歉,孤山望月礼+蛋黄酥(7只装)仅限提货券用户购买");
					}
					var ticketreq = new GetTicticketReq { Cardno = request.DiscountList[0].CardNo, Pagesize = 200, State = 2, Pageindex = 1 };
					Iclogger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
					var a = await NetICService.Geticticket(ticketreq).ConfigureAwait(false);
					if (a.code == 0) {
						var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
						var ticket = list.Tickets.SingleOrDefault(t => t.Ticketid == request.DiscountList[0].DiscountCouponId);
						if (ticket != null) {
							request.DiscountList[0].DiscountCouponMoney = ticket.Je.ToDecimal(0);
							ticketInfoPrice = request.DiscountList[0].DiscountCouponMoney;
							Discount = ticketInfoPrice;
						} else {
							return new BaseResult<MallOrderPreviewReponse>(null, -23, "优惠券不可用");
						}

					} else {
						return new BaseResult<MallOrderPreviewReponse>(null, -23, "优惠券不可用");
					}
					var tt = new List<long>() { request.DiscountList[0].DiscountCouponId };
					ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, tt, 1, true).ConfigureAwait(false);
				}
				else if (request.DiscountList[0].DiscountCouponType == 2) {
					var memberCoupon = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(request.DiscountList[0].DiscountCouponId).ConfigureAwait(false);
					if (memberCoupon == null || memberCoupon.MID != entity.ID) {
						return new BaseResult<MallOrderPreviewReponse>(null, 9999, "券不存在");
					}
					if (memberCoupon.Productid == 589821) {
						FreightMoney = 0;
					} else {
						if (request.GoodsList.Any(c => c.GoodsRelationId == 589873)) {
							return new BaseResult<MallOrderPreviewReponse>(null, 9999, "抱歉,孤山望月礼+蛋黄酥(7只装)仅限提货券用户购买");
						}
					}
					var ticketInfoRsp = await NetICService.Tmticketquery(new Domain.Request.IC.TmticketqueryReq { ticketcode = memberCoupon.Ticketcode }).ConfigureAwait(false);
					if (ticketInfoRsp.code != 0) {

						return new BaseResult<MallOrderPreviewReponse>(null, ticketInfoRsp.code, ticketInfoRsp.msg);

					}
					var ticketInfo = JObject.Parse(ticketInfoRsp.content);

					ticketInfoPrice = memberCoupon.Price;
					 
					//a.Productname = ticketInfo["productname"].ToString();
					//a.Productid = ticketInfo["productid"].ToInt64(0);
					var State = ticketInfo["state"].ToInt16(0);
					//a.Startdate = DateTime.Parse(ticketInfo["startdate"].ToString(), CultureInfo.InvariantCulture);
					//a.Enddate = DateTime.Parse(ticketInfo["enddate"].ToString(), CultureInfo.InvariantCulture);
					if (State != 3) {
						return new BaseResult<MallOrderPreviewReponse>(null, 9999, "券不可用");
					}
					var ids = new List<long> {
								ticketInfo["productid"].ToInt64(0)
							};
					ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId,ids,0,false).ConfigureAwait(false);
					//ticketLimit = await NetICService.TicketLimit(storeInfo.RelationId, memberCoupon.Ticketcode).ConfigureAwait(false);
				} else {
					return new BaseResult<MallOrderPreviewReponse>(null, 9999, "券类型有误");
				}
				var rule = JsonConvert.DeserializeObject<TicketsRules>(ticketLimit.content);
				//51、当前券要求最低的单据金额，limitvalue为单据金额
				//21、券仅允许消费的产品，limitvalue 为限制的产品标识
				//215、券必须消费的产品，limitvalue 为限制的产品标识
				//216、券需要消费的产品(之一)，limitvalue 为限制的产品标识，和 215 不同，216 只需要有一种产品就可以了，如果 limitvalue 只有一种产品，则和 215 效果相同
				//22、券不允许消费的产品，limitvalue 为限制的产品标识
				Discount = ticketInfoPrice;
				var list216 = rule.Tickets.Where(c => c.Limittype == 216);
				if (list216.Any()) {
					bool s = false;
					var list216msg = "";
					foreach (var item in list216) {
						var ss = request.GoodsList.Count(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture));
						if (ss > 0) {
							s = true;
						} else {
							list216msg += $"{item.Productname}{item.Limitdesc}";
						}
					}
					if (!s) {
						//list.Tickets[i].State = 0;
						return new BaseResult<MallOrderPreviewReponse>(null, 9999, list216msg);
					}
					Discount = ticketInfoPrice;
				}

				var list215 = rule.Tickets.Where(c => c.Limittype == 215);
				if (list215.Any()) {
					var list215sucess = true;
					var amsg = "";
					foreach (var item in list215) {
						if (!request.GoodsList.Any(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture))) {
							amsg += $"{item.Productname}{item.Limitdesc}";
							list215sucess = false;
						}
					}
					if (!list215sucess) {
						//list.Tickets[i].State = 0;
						return new BaseResult<MallOrderPreviewReponse>(null, 9999, amsg);
					}
					//Discount = ticketInfoPrice;
				}
				var abc = rule.Tickets;
				foreach (var item in abc) {
					if (item.Limittype == 51) {
						var tamount = OrderAmount;

						if (tamount < item.Limitvalue.ToDecimal(0)) {
							//list.Tickets[i].State = 0;
							return new BaseResult<MallOrderPreviewReponse>(null, 9999, item.Limitdesc);
						}
						//Discount = ticketInfoPrice;
					}
					if (item.Limittype == 21) {
						var aa = request.GoodsList.Where(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture)).ToList();
						if (aa.Any()) {
							//list.Tickets[i].State = 0;
							return new BaseResult<MallOrderPreviewReponse>(null, 9999, item.Limitdesc);
						}
						//Discount = aa[0].Price;
					}
					if (item.Limittype == 22) {
						var aa = request.GoodsList.Count(c => c.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture));
						if (aa > 0) {
							//list.Tickets[i].State = 0;
							return new BaseResult<MallOrderPreviewReponse>(null, 9999, item.Limitdesc);
						}
						Discount = ticketInfoPrice;
					}
				}
			}
			var rsp = new MallOrderPreviewReponse {
				FreightMoney = FreightMoney,
				Discount=Discount,
				OrderAmount = OrderAmount + FreightMoney,
				PayAmount = OrderAmount - Discount + FreightMoney
			};
			return new BaseResult<MallOrderPreviewReponse>(rsp, 0, "");
		}
	}
}
